<!--
 * @Author: your name
 * @Date: 2022-04-09 13:32:40
 * @LastEditTime: 2022-06-18 13:54:56
 * @LastEditors: Dweriout 2428458948@qq.com
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \nien-vue3-admin\src\views\system\user\index.vue
-->
<template>
  <div class="app-container">
    <el-container>
      <el-main class="tableArea">
        <custom-container
          ref="customContainerRef"
          :config="mainConfig"
        ></custom-container>
        <setForm
          ref="setFormRef"
          v-model:open="open"
          v-model:title="title"
          :dept-options="deptOptions"
          @changeList="handleQuery"
        />
      </el-main>
    </el-container>
  </div>
</template>
<script lang="ts" setup>
import {
  ref,
  computed,
  getCurrentInstance,
  defineAsyncComponent,
} from 'vue'
import { ElTree, ElButton, ElMessageBox, ElMessage, ElSwitch } from 'element-plus'

import {
  Plus,
  Edit,
  Delete,
  Bottom,
  Key,
} from '@element-plus/icons-vue'
import { useI18n } from 'vue-i18n'
import { treeselect } from '@/api/system/dept'
import { DictDirection } from '@/store/modules/dicts'
import {
  listUserTab,
  delUser,
  resetUserPwd,
  changeUserStatus,
  passwordDecryption,
} from '@/api/system/user'
import {
  isTest,
} from '@/utils/index'

const setForm = defineAsyncComponent(() => import('./components/setForm.vue'))
const { t } = useI18n()

// 非单个禁用
const single = ref(true),
  // 非多个禁用
  multiple = ref(true),
  // 添加或修改配置参数对话框
  open = ref(false),
  title = ref(''),
  // 查询参数
  queryParams = ref({
    pageNum: 1,
    pageSize: 10,
    userType: '02', 
    userClassify: '1',
    userName: undefined,
  }),

  // 搜索表单
  // queryFormRef = ref(null),
  customContainerRef = ref(null),
  setFormRef = ref(undefined),
  {
    appContext: {
      config: {
        globalProperties: { $download },
      },
    },
    proxy,
  } = getCurrentInstance()
//
let ids = []
// 搜索
const handleQuery = () => {
  customContainerRef.value.pageNum = 1
  customContainerRef.value.getList()
}
// 新增客户
const handleAdd = (row: { deptId?: number } | MouseEvent) => {
  open.value = true
  title.value = '新增客户'
  if ('deptId' in row) {
    setFormRef.value.listForms.deptId = row.deptId
  } else {
    setFormRef.value.listForms.deptId = 100
  }
  setFormRef.value.getUserDetail()
}
const deptOptions = ref([])
// 列表选择
const handleSelectionChange = (rows: { [key: string]: any }[]) => {
  ids = rows.map((item) => item.userId)
  single.value = rows.length != 1
  multiple.value = !rows.length
}
// 修改
const handleUpdate = (row: { [key: string]: any }) => {
  open.value = true
  title.value = '修改客户'
  const userId = row?.userId || ids
  setFormRef.value.getList(userId)
}
// 删除
const handleDelete = (row: { [key: string]: any }) => {
  const userId = row.userId || ids
  ElMessageBox.confirm(`是否确认删除客户编号为"${ userId }"的数据项?`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
  .then(() => delUser(userId))
  .then((res) => {
    if (res.code === 200) {
      ElMessage.success('删除成功')
      handleQuery()
    } else {
      ElMessage.error(res.msg)
    }
  })
  .catch((error) => {
    if (error == 'cancel') {
      ElMessage.info('取消删除')
    }
  })
}
// 客户导出
const handleExport = () => {
  $download(
    'system/user/export',
    { ...queryParams.value },
    `客户信息_${ new Date().getTime() }.xlsx`,
  )
}

// 重置密码
const handleResetPwd = (row: { [key: string]: any }) => {
  if (isTest()) {
    ElMessageBox.prompt(`请输入${ row.userName }的新密码`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
    }).then(({ value }) => {
      resetUserPwds(row.userId, value)
    })
  } else {
    resetUserPwds(row.userId, '123456')
  }
}
const resetUserPwds = (userId, v) => {
  resetUserPwd(userId, v).then((res) => {
    res.code == 200 && alert(res.msg)
  })
}
/** 客户状态修改  */
const emit = defineEmits(['update:modelValue'])
// 修改状态
const handleStatusChange = (row: { [key: string]: any }) => {
  const text = row.status == 1 ? '启用' : '停用'
  row.status = row.status === 0 ? 1 : 0
  ElMessageBox.confirm(`确认要"${ text }""${ row.userName }"客户吗?`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
  .then(() => changeUserStatus(row.userId, row.status))
  .then((res) => {
    if (res.code == 200) {
      ElMessage.success(`${ text }成功`)
      handleQuery()
    } 
  })
  .catch((error) => {
    if (error === 'cancel') {
      ElMessage.info('取消操作')
    }
  })
}
// 客户账号解密
const handlerStartOrForbidden = (v) => {
  if (v.includes('解密')) {
    const userName = queryParams.value.userName
    if (userName == '' || userName == undefined || userName == null) {
      ElMessage.error('客户名称未输入')
      return
    }
    passwordDecryption(queryParams.value.userName).then(res => {
      if (res.code == 200) {
        alert(res.data[0])
      }
    })
  }
  handleQuery()
}
const mainConfig = computed(() => {
  const queryField = 'system.customerAccountSettings.queryField.'
  const btns = 'system.customerAccountSettings.btns.'
  const columns = 'system.customerAccountSettings.columns.'
  const publicKey = 'public.'
  return {
    query: {
      fields: [
        {
          label: t(`${ queryField }userName`),
          prop: 'userName',
          minWidth: '55px',
          option: {
            placeholder: '请输入客户名称',
          },
        },
        {
          label: t(`${ queryField }phoneNumber`),
          prop: 'phoneNumber',
          option: {
            placeholder: '请输入手机号码',
          },
        },
        {
          label: t(`${ queryField }status`),
          prop: 'status',
          type: 'select',
          option: {
            placeholder: '请输入状态',
            dictInfo: {
              dict: DictDirection.是否禁用字典,
            },
          },
        },
        {
          type: 'datePicker',
          label: t(`${ queryField }dateRange`),
          prop: 'dateRange',
          option: {
            type: 'daterange',
            placeholder: '开始时间-结束时间',
          },
        },
      ],
      queryParams: queryParams.value,
    },
    btns: [
      {
        title: t(`${ btns }add`),
        directive: [['hasPermi', ['system:customer:add']]],
        onclick: handleAdd,
        icon: Plus,
      },
      {
        title: t(`${ btns }edit`),
        directive: [['hasPermi', ['system:customer:edit']]],
        type: 'success',
        disabled: multiple.value,
        icon: Edit,
        onClick: handleUpdate,
      },
      {
        title: t(`${ btns }del`),
        directive: [['hasPermi', ['system:customer:remove']]],
        onClick: handleDelete,
        type: 'danger',
        disabled: multiple.value,
        icon: Delete,
      },
      {
        title: t(`${ btns }export`),
        onclick: handleExport,
        type: 'warning',
        icon: Bottom,
        directive: [['hasPermi', ['system:customer:export']]],
      },
      {
        title: t(`${ btns }decryption`),
        onclick: handlerStartOrForbidden,
        type: 'success',
        icon: Bottom,
        directive: [['hasPermi', ['system:pswd:parse']]],
      },
    ],
    table: {
      columns: [
        {
          type: 'selection',
          minWidth: '55',
          align: 'center',
        },
        {
          label: t(`${ columns }userId`),
          prop: 'userId',
          align: 'center',
        },
        {
          label: t(`${ columns }userName`),
          prop: 'userName',
          align: 'center',
        },
        {
          label: t(`${ columns }nickName`),
          prop: 'nickName',
          align: 'center',
        },
        {
          label: t(`${ columns }deptName`),
          prop: 'deptName',
          align: 'center',
        },
        {
          label: t(`${ columns }phoneNumber`),
          prop: 'phoneNumber',
          align: 'center',
        },
        {
          label: t(`${ columns }status`),
          prop: 'status',
          align: 'center',
          directive: [['hasPermi', ['system:user:editStatus'], 'switch']],
          autoFormatter: {
            dict: DictDirection.通用状态,
            rowKey: 'status',
          },
          render(h, params) {
            return h(ElSwitch, {
              onClick: () => {
                handleStatusChange(params.row)
                console.log('handleStatusChange', params)
              },
              modelValue: params.row.status,
              'onUpdate:modelValue': (value) => {
                emit('update:modelValue', value)
              },
              activeValue: 1,
              inactiveValue: 0,
              activeColor: '#C0CCDA',
              inactiveColor: '#409EFF',
            })
          },
        },
        {
          label: t(`${ columns }createTime`),
          prop: 'createTime',
          align: 'center',
        },
        {
          label: t(`${ columns }operation`),
          align: 'center',
          showOverflowTooltip: false,
          fixed: 'right',
          width: '250',
          render: (h, params) => {
            const buttons = [
              {
                title: t(`${ publicKey }edit`),
                icon: Edit,
                clickFun: handleUpdate,
                directive: [['hasPermi', ['system:customer:edit']]],
              },
              {
                title: t(`${ publicKey }del`),
                icon: Delete,
                clickFun: handleDelete,
                directive: [['hasPermi', ['system:customer:remove']]],
              },
              {
                title: t(`${ publicKey }reset`),
                icon: Key,
                clickFun: handleResetPwd,
                directive: [['hasPermi', ['system:customer:resetPwd']]],
              },
            ]
            return buttons.map((el) => h(
              ElButton,
              {
                text: true,
                type: 'primary',
                icon: el.icon,
                onClick: () => {
                  el.clickFun(params.row)
                },
              },
              {
                default: () => el.title,
              },
            ))
          },
        },
      ],
      event: {
        onSelectionChange: (rows) => {
          handleSelectionChange(rows)
        },
      },
    },
    api: listUserTab,
    customKey: 'system/accountManagement/customerAccountSettings',
  }
})
</script>
<style lang="less" scoped>
.head-dept {
  margin: 20px 0;
}
:deep(.head-dept>.head) {
  height: 30px;
}
.head-container {
  overflow: hidden;
  overflow-y: hidden;
  min-width: 250px;
  background-color: #fff;
}
/* stylelint-disable-next-line no-descending-specificity */
:deep(.el-tree) {
  overflow: hidden;
  overflow-y: scroll;
  min-width: 250px;
  & > .el-tree-node {
    padding-top: 20px;
  }
  &::-webkit-scrollbar {
    min-width: 5px !important;
    height: 3px !important;
    background-color: #eee;
  }
  &::-webkit-scrollbar-thumb {
    border-radius: 10px;
    background: rgb(0 0 0 / 0.2);
    height: 5px !important;
  }
}
</style>
